import { ref, computed } from 'vue'

export interface IHistoryRecord {
  id: string
  type: 'add' | 'edit' | 'delete' | 'move' | 'style' | 'props'
  title: string
  description?: string
  timestamp: number
  data: any
  componentId?: string
  previousState?: any
  newState?: any
}

export interface IHistoryAction {
  action: 'go-to' | 'clear'
  index?: number
}

export function useHistoryManager() {
  // 历史记录
  const historyRecords = ref<IHistoryRecord[]>([])
  
  // 当前历史记录索引
  const currentIndex = ref(-1)
  
  // 最大历史记录数量
  const maxHistorySize = 100
  
  // 计算属性
  const canUndo = computed(() => currentIndex.value > 0)
  const canRedo = computed(() => currentIndex.value < historyRecords.value.length - 1)
  const historyCount = computed(() => historyRecords.value.length)
  
  // 添加历史记录
  const addHistoryRecord = (record: Omit<IHistoryRecord, 'id' | 'timestamp'>) => {
    const newRecord: IHistoryRecord = {
      ...record,
      id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      timestamp: Date.now()
    }
    
    // 如果当前不在最新位置，删除后面的记录
    if (currentIndex.value < historyRecords.value.length - 1) {
      historyRecords.value = historyRecords.value.slice(0, currentIndex.value + 1)
    }
    
    // 添加新记录
    historyRecords.value.push(newRecord)
    currentIndex.value = historyRecords.value.length - 1
    
    // 限制历史记录数量
    if (historyRecords.value.length > maxHistorySize) {
      historyRecords.value.shift()
      currentIndex.value = Math.max(0, currentIndex.value - 1)
    }
    
    return newRecord
  }
  
  // 撤销
  const undo = () => {
    if (canUndo.value) {
      currentIndex.value--
      const record = historyRecords.value[currentIndex.value]
      return {
        record,
        action: 'undo',
        previousState: record.previousState,
        newState: record.newState
      }
    }
    return null
  }
  
  // 重做
  const redo = () => {
    if (canRedo.value) {
      currentIndex.value++
      const record = historyRecords.value[currentIndex.value]
      return {
        record,
        action: 'redo',
        previousState: record.previousState,
        newState: record.newState
      }
    }
    return null
  }
  
  // 跳转到指定历史记录
  const goToHistory = (index: number) => {
    if (index >= 0 && index < historyRecords.value.length) {
      currentIndex.value = index
      const record = historyRecords.value[index]
      return {
        record,
        action: 'go-to',
        previousState: record.previousState,
        newState: record.newState
      }
    }
    return null
  }
  
  // 清空历史记录
  const clearHistory = () => {
    historyRecords.value = []
    currentIndex.value = -1
  }
  
  // 获取历史记录列表
  const getHistoryList = () => {
    return historyRecords.value.map((record, index) => ({
      ...record,
      isActive: index === currentIndex.value
    }))
  }
  
  // 获取当前历史记录
  const getCurrentRecord = () => {
    if (currentIndex.value >= 0 && currentIndex.value < historyRecords.value.length) {
      return historyRecords.value[currentIndex.value]
    }
    return null
  }
  
  // 检查是否有未保存的更改
  const hasUnsavedChanges = computed(() => {
    return historyRecords.value.length > 0 && currentIndex.value < historyRecords.value.length - 1
  })
  
  // 创建组件添加记录
  const createAddRecord = (component: any, previousState?: any) => {
    return addHistoryRecord({
      type: 'add',
      title: `添加${component.name || component.type}组件`,
      description: `在页面中添加了${component.name || component.type}组件`,
      data: { component },
      componentId: component.id,
      previousState,
      newState: { component }
    })
  }
  
  // 创建组件编辑记录
  const createEditRecord = (componentId: string, previousState: any, newState: any, field?: string) => {
    const fieldName = field || '属性'
    return addHistoryRecord({
      type: 'edit',
      title: `修改${fieldName}`,
      description: `修改了组件的${fieldName}`,
      data: { componentId, field, previousState, newState },
      componentId,
      previousState,
      newState
    })
  }
  
  // 创建组件删除记录
  const createDeleteRecord = (component: any, previousState?: any) => {
    return addHistoryRecord({
      type: 'delete',
      title: `删除${component.name || component.type}组件`,
      description: `从页面中删除了${component.name || component.type}组件`,
      data: { component },
      componentId: component.id,
      previousState,
      newState: null
    })
  }
  
  // 创建组件移动记录
  const createMoveRecord = (componentId: string, previousPosition: any, newPosition: any) => {
    return addHistoryRecord({
      type: 'move',
      title: '移动组件',
      description: '移动了组件位置',
      data: { componentId, previousPosition, newPosition },
      componentId,
      previousState: { position: previousPosition },
      newState: { position: newPosition }
    })
  }
  
  // 创建样式修改记录
  const createStyleRecord = (componentId: string, previousStyle: any, newStyle: any) => {
    return addHistoryRecord({
      type: 'style',
      title: '修改样式',
      description: '修改了组件样式',
      data: { componentId, previousStyle, newStyle },
      componentId,
      previousState: { style: previousStyle },
      newState: { style: newStyle }
    })
  }
  
  // 创建属性修改记录
  const createPropsRecord = (componentId: string, previousProps: any, newProps: any) => {
    return addHistoryRecord({
      type: 'props',
      title: '修改属性',
      description: '修改了组件属性',
      data: { componentId, previousProps, newProps },
      componentId,
      previousState: { props: previousProps },
      newState: { props: newProps }
    })
  }
  
  // 批量操作记录
  const createBatchRecord = (operations: Array<Omit<IHistoryRecord, 'id' | 'timestamp'>>, title: string) => {
    return addHistoryRecord({
      type: 'edit',
      title,
      description: `批量操作：${operations.length}个操作`,
      data: { operations },
      previousState: operations.map(op => op.previousState),
      newState: operations.map(op => op.newState)
    })
  }
  
  return {
    // 状态
    historyRecords,
    currentIndex,
    canUndo,
    canRedo,
    historyCount,
    hasUnsavedChanges,
    
    // 方法
    addHistoryRecord,
    undo,
    redo,
    goToHistory,
    clearHistory,
    getHistoryList,
    getCurrentRecord,
    
    // 便捷方法
    createAddRecord,
    createEditRecord,
    createDeleteRecord,
    createMoveRecord,
    createStyleRecord,
    createPropsRecord,
    createBatchRecord
  }
}
